package com.z.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.z.common.web.vo.request.PageVo;
import com.z.sys.entity.Permission;
import com.z.sys.entity.RolePermission;
import com.z.sys.mapper.PermissionMapper;
import com.z.sys.service.IPermissionService;
import com.z.sys.service.IRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * 权限资源管理Service业务层处理
 *
 * @author z
 * @date 2022-11-07
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper,Permission> implements IPermissionService {


    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private PermissionMapper permissionMapper;
    /**
     * 查询权限资源管理
     * @param permission 权限资源管理
     * @param pageVo
     * @return 权限资源管理 分页集合
     * */
    @Override
    public PageInfo<Permission> selectPermissionPage(Permission permission, PageVo pageVo) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<Permission> data = baseMapper.selectPermissionList(permission);
        return new PageInfo<>(data);
    }

    @Override
    public List<Permission> selectPermissionList(Permission permission) {
        permission.setDel(false);
        return baseMapper.selectPermissionList(permission);
    }

    @Override
    @Transactional
    public boolean removeByIdAndPid(Long id) {
        List<Long> idList = new ArrayList<>();
        idList.add(id);
        List<Long> tlist = permissionMapper.listIdListByPid(id);
        while ( tlist!=null && tlist.size()>0){
            idList.addAll(tlist);
            tlist = permissionMapper.listIdListByPids(tlist);
        }
        log.debug(idList.toString());
        rolePermissionService.update(new UpdateWrapper<RolePermission>().set("del", 1).in("permission_id", idList));
        update(new UpdateWrapper<Permission>().in("id", idList).set("del", 1));
        return true;
    }

    @Override
    @Transactional
    public boolean removeByIds(Collection<?> ids) {
        for(Object id : ids){
            removeByIdAndPid((Long) id);
        }
        return true;
    }
}
